<template>
  <NavTitle title="字符变量" />
  <Table
    ref="tableRef"
    :columns="columns"
    :data="loadData"
    :alert="false"
    bordered
    :showPagination="false"
    :row-key="(record: any) => record.id"
  >
    <template #operator>
      <div class="table-button" v-if="!isView">
        <a-button type="primary" ghost @click="addStringOpen">
          <SvgIcon class="iconDef" :name="'addPush'" :color="'#2590FF'" width="16" height="16" />
          新增字符变量
        </a-button>
      </div>
    </template>
    <template #bodyCell="{ column, record, index }">
      <template v-if="column.dataIndex === 'isPrivate'">
        <a-switch
          v-model:checked="record.isPrivate"
          :checkedValue="1"
          :unCheckedValue="0"
          checked-children="开"
          un-checked-children="关"
          :disabled="isView || isIfCommon(record)"
        />
      </template>
      <template v-if="column.dataIndex === 'isRunSetting'">
        <a-switch
          v-model:checked="record.isRunSetting"
          :checkedValue="1"
          :unCheckedValue="0"
          checked-children="开"
          un-checked-children="关"
          :disabled="isView || isIfCommon(record)"
        />
      </template>
      <template v-if="column.dataIndex === 'action'">
        <div class="table-operation" v-if="!isView && !isIfCommon(record)">
          <SvgIcon
            class="iconDef"
            :name="'delete'"
            :color="'#6d85a6'"
            width="16"
            height="16"
            @click="deleteVariable(record, index)"
          />
        </div>
      </template>
    </template>
  </Table>
  <NavTitle title="运行选择变量" style="margin-top: 40px" />
  <Table
    ref="tableSelectRef"
    :columns="columnsSelect"
    :data="loadDataSelect"
    :alert="false"
    bordered
    :showPagination="false"
    :row-key="(record: any) => record.id"
  >
    <template #operator>
      <div class="table-button" v-if="!isView">
        <a-button type="primary" ghost @click="addWorkingOpen">
          <SvgIcon class="iconDef" :name="'addPush'" :color="'#2590FF'" width="16" height="16" />
          新增运行选择变量
        </a-button>
      </div>
    </template>
    <template #bodyCell="{ column, record, index }">
      <template v-if="column.dataIndex === 'action'">
        <div class="table-operation" v-if="!isView">
          <SvgIcon
            class="iconDef"
            :name="'edit2'"
            :color="'#6d85a6'"
            width="16"
            height="16"
            @click="editWorking(record, index)"
          />
          <SvgIcon
            class="iconDef"
            :name="'delete'"
            :color="'#6d85a6'"
            width="16"
            height="16"
            @click="deleteWorking(record, index)"
          />
        </div>
      </template>
    </template>
  </Table>

  <BasicModal ref="addStringModal" :title="titleStringName" width="400px" @emit-callback-fn="addStringCallbackFn">
    <template #content>
      <schemaStringForm ref="formStringRef" />
    </template>
  </BasicModal>

  <BasicModal ref="addModal" :title="titleName" width="400px" @emit-callback-fn="addCallbackFn($event)">
    <template #content>
      <schemaForm ref="formRef" />
    </template>
  </BasicModal>
</template>

<script lang="ts" setup>
import { useForm } from '@/components/SchemaForm/index';
import { Modal } from 'ant-design-vue';
import { createVNode } from 'vue';
import { usePipelineStore } from '@/store/modules/pipeline';
import { storeToRefs } from 'pinia';
import { cloneDeep } from 'lodash';
import { PipelineOperationTypeCode } from '@/enums/pipelineEnum';
import { SystemBuiltInVariables } from '@/enums/commonEnum';
const route = useRoute();
const counterStore = usePipelineStore();
const { variableSettingList } = storeToRefs(counterStore);
const { setVariablesData } = counterStore;
const dataObject = ref<any>(cloneDeep(variableSettingList));
const getVariablesData = computed(() => {
  return dataObject.value;
});
const isView = computed(() => route.params.type == PipelineOperationTypeCode.info);
const isIfCommon = (record: any) => {
  return record.isCommon == SystemBuiltInVariables.DEFAULT;
};
const titleStringName = ref('');
const addStringModal = ref<any>(null);
const [schemaStringForm, formStringRef] = useForm({
  schemas: [
    {
      field: 'name',
      label: '变量名',
      labelWidth: 80,
      required: true,
      colProps: {
        span: 24,
      },
      component: 'Input',
    },
    {
      field: 'defaultValue',
      label: '默认值',
      labelWidth: 80,
      required: true,
      colProps: {
        span: 24,
      },
      component: 'Input',
    },
  ],
});
//字符列表
const characterList = ref<Pipeline.VariableSetting[]>([]);
//运行选择列表
const workingList = ref<Pipeline.VariableSetting[]>([]);
const columns = [
  { dataIndex: 'name', title: '变量名称', align: 'center' },
  { dataIndex: 'defaultValue', title: '默认值', align: 'center' },
  { dataIndex: 'isPrivate', title: '私密模式', align: 'center' },
  { dataIndex: 'isRunSetting', title: '运行时设置', align: 'center' },
  {
    title: '操作',
    dataIndex: 'action',
    align: 'center',
    fixed: 'right',
    width: 220,
  },
];
const tableRef = ref<any>(null);
//新增字符变量
const addStringOpen = () => {
  addStringModal.value.showModal();
  titleStringName.value = '新增字符变量';
  formStringRef.resetFields();
};
//新增字符变量
const addStringCallbackFn = async () => {
  const data = await formStringRef.validate();
  characterList.value.push({
    pipelineCode: route.params.code as string, // 流水线编码
    name: data.name, // 变量名称
    defaultValue: data.defaultValue, // 默认值
    isPrivate: 0, // 私密模式，1开启0关闭
    isRunSetting: 0, // 运行时设置，1开启0关闭
    option: '', // 选项，待定义
    isRunSelect: 0, // 是否运行选择变量，1是0否
  });
  addStringModal.value.hideModal();
};

//删除字符变量
const deleteVariable = (record: any, index: number) => {
  Modal.confirm({
    title: '提示',
    icon: '',
    centered: true,
    content: createVNode('div', { style: 'color:black;' }, `确定要删除“字符变量：${record.name}”这一项数据吗？`),
    async onOk() {
      characterList.value.splice(index, 1);
      // message.success('删除成功');
    },
    onCancel() {},
    class: 'test',
  });
};
const loadData = async () => {
  return characterList.value;
};
enum modelType {
  add = '新增运行选择变量',
  edit = '编辑运行选择变量',
}
const titleName = ref('');
const addModal = ref<any>(null);
const [schemaForm, formRef] = useForm({
  schemas: [
    {
      field: 'name',
      label: '变量名',
      labelWidth: 80,
      required: true,
      colProps: {
        span: 24,
      },
      component: 'Input',
    },
    {
      field: 'defaultValue',
      label: '默认值',
      labelWidth: 80,
      required: true,
      colProps: {
        span: 24,
      },
      component: 'Input',
    },
    {
      field: 'option',
      label: '选项',
      labelWidth: 80,
      required: false,
      colProps: {
        span: 24,
      },
      component: 'Input',
    },
  ],
});

const columnsSelect = [
  { dataIndex: 'name', title: '变量名称', align: 'center' },
  { dataIndex: 'defaultValue', title: '默认值', align: 'center' },
  { dataIndex: 'option', title: '选项', align: 'center' },
  {
    title: '操作',
    dataIndex: 'action',
    align: 'center',
    fixed: 'right',
    width: 220,
  },
];

const loadDataSelect = async () => {
  return workingList.value;
};
//新增运行变量
const addWorkingOpen = () => {
  addModal.value.showModal();
  titleName.value = modelType.add;
  formRef.resetFields();
};
//新增运行变量
const addCallbackFn = async (obj: any) => {
  const data = await formRef.validate();
  if (titleName.value == modelType.add) {
    workingList.value.push({
      name: data.name, // 变量名称
      defaultValue: data.defaultValue, // 默认值
      isPrivate: 0, // 私密模式，1开启0关闭
      isRunSetting: 0, // 运行时设置，1开启0关闭
      option: data.option, // 选项，待定义
      isRunSelect: 1, // 是否运行选择变量，1是0否
      pipelineCode: route.params.code as string, // 流水线编码
    });
  } else {
    workingList.value[obj.propsData.index] = { ...obj.propsData, ...data };
  }

  addModal.value.hideModal();
};
//编辑运行变量
const editWorking = (record: any, index: number) => {
  nextTick(() => {
    formRef.setFieldsValue(record);
  });
  addModal.value.showModal({ ...record, index });
  titleName.value = modelType.edit;
};

//删除运行变量
const deleteWorking = (record: any, index: number) => {
  Modal.confirm({
    title: '提示',
    icon: '',
    centered: true,
    content: createVNode('div', { style: 'color:black;' }, `确定要删除“运行选择变量：${record.name}”这一项数据吗？`),
    async onOk() {
      workingList.value.splice(index, 1);
      // message.success('删除成功');
    },
    onCancel() {},
    class: 'test',
  });
};

const getTableList = computed(() => {
  return [...workingList.value, ...characterList.value];
});

enum RunSelect {
  isRun = 1,
  notRun = 0,
}
watch(
  getVariablesData,
  (newVal) => {
    if (newVal && newVal.length > 0) {
      dataObject.value = cloneDeep(newVal);
      characterList.value = dataObject.value.filter((item: any) => item.isRunSelect == RunSelect.notRun);
      workingList.value = dataObject.value.filter((item: any) => item.isRunSelect == RunSelect.isRun);
    }
  },
  {
    immediate: true,
  },
);

watch(
  getTableList,
  (newVal) => {
    if (newVal) {
      setVariablesData(newVal);
    }
  },
  { deep: true },
);
</script>

<style scoped lang="less">
.table-button {
  margin-top: 16px;
  display: flex;
  button {
    margin: 0 6px;
    display: flex;
    align-items: center;
  }
  .iconDef {
    cursor: pointer;
    margin-right: 8px;
  }
}
</style>
